package com.zyh.record.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyh.answer.domain.AnalyzeDataObj;
import com.zyh.answer.domain.UserAnswer;
import com.zyh.answer.mapper.UserAnswerMapper;
import com.zyh.answer.service.UserAnswerService;
import com.zyh.common.core.domain.AjaxResult;
import com.zyh.common.utils.SecurityUtils;
import com.zyh.record.domain.ExamRecord;
import com.zyh.record.mapper.ExamRecordMapper;
import com.zyh.record.service.ExamRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 针对表【t_exam_record】的数据库操作Service实现
 *
 * @author ZYH
 * @description
 * @createDate 2025-03-02 20:29:11
 */
@Service
public class ExamRecordServiceImpl extends ServiceImpl<ExamRecordMapper, ExamRecord>
        implements ExamRecordService {
    public static final Logger logger = LoggerFactory.getLogger(ExamRecordServiceImpl.class);

    @Autowired
    private ExamRecordMapper examRecordMapper;
    @Autowired
    private UserAnswerMapper userAnswerMapper;
    @Autowired
    private UserAnswerService userAnswerService;

    /**
     * 计算分数
     *
     * @param record
     * @return
     */
    @Override
    public int submitPaper(ExamRecord record) {
        // 计算总分 根据userId,paperId,recordId查询出所有的answer对象
        List<UserAnswer> userAnswerList = userAnswerMapper.selectList(
                new LambdaQueryWrapper<UserAnswer>()
                        .eq(UserAnswer::getUserId, record.getUserId())
                        .eq(UserAnswer::getPaperId, record.getPaperId())
                        .eq(UserAnswer::getRecordId, record.getId()));
        // 通过stream流获取每个answer的score并累加
        int totalScore = userAnswerList.stream().map(UserAnswer::getScore).mapToInt(Integer::intValue).sum();
        record.setTotalScore(totalScore);
        return examRecordMapper.updateById(record);
    }

    @Override
    public AjaxResult addAnswer(UserAnswer userAnswer) {
        userAnswer.setUserId(SecurityUtils.getUserId());    // 设置用户id
        userAnswer.setAnswerTime(new Date());   // 更新答题时间
        userAnswer.setCreateBy(SecurityUtils.getUsername());
        // 将answer转为json，格式为 {"A":1,"B":2,"C":3}
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("\"");
        sb.append(userAnswer.getAnswer());
        sb.append("\":");
        sb.append(userAnswer.getScore());
        sb.append("}");
        userAnswer.setAnswer(sb.toString());
        if (Objects.isNull(userAnswer.getScore())) {
            userAnswer.setScore(0);     // 设置分数默认值
        }
        ExamRecord examRecord = examRecordMapper.selectOne(
                new LambdaQueryWrapper<ExamRecord>()
                        .eq(ExamRecord::getUserId, SecurityUtils.getUserId())
                        .eq(ExamRecord::getPaperId, userAnswer.getPaperId())
                        .eq(ExamRecord::getDelFlag, "0"));
        if (Objects.isNull(examRecord)) {
            return AjaxResult.error("查询测评记录为空");
        }
        userAnswer.setRecordId(examRecord.getId());
        // 查询是否有该答题记录
        UserAnswer getUserAnswer = userAnswerMapper.selectOne(
                new LambdaQueryWrapper<UserAnswer>()
                        .eq(UserAnswer::getUserId, userAnswer.getUserId())
                        .eq(UserAnswer::getPaperId, userAnswer.getPaperId())
                        .eq(UserAnswer::getQuestionId, userAnswer.getQuestionId())
                        .eq(UserAnswer::getRecordId, userAnswer.getRecordId())
                        .eq(UserAnswer::getDelFlag, "0")
        );
        // 如果为空，说明该题没有答题记录
        if (Objects.isNull(getUserAnswer)) {
            logger.info("新增答题记录");
            return userAnswerMapper.insert(userAnswer) > 0 ? AjaxResult.success() : AjaxResult.error();
        } else {
            logger.info("更新答题记录");
            // 更新答题记录
            return userAnswerMapper.update(userAnswer,
                    new LambdaQueryWrapper<UserAnswer>()
                            .eq(UserAnswer::getUserId, userAnswer.getUserId())
                            .eq(UserAnswer::getPaperId, userAnswer.getPaperId())
                            .eq(UserAnswer::getQuestionId, userAnswer.getQuestionId())
                            .eq(UserAnswer::getRecordId, userAnswer.getRecordId())
            ) > 0 ? AjaxResult.success() : AjaxResult.error();
        }
    }

    /**
     * 比对历史记录
     *
     * @param currentId
     * @param historyId
     * @return
     */
    @Override
    public AjaxResult compareHistoryRecord(Long currentId, Long historyId) {
        ExamRecord currentRecord = examRecordMapper.selectById(currentId);
        ExamRecord historyRecord = examRecordMapper.selectById(historyId);
        if (Objects.isNull(currentRecord) || Objects.isNull(historyRecord)) {
            return AjaxResult.error("查询历史记录为空");
        }
        // 根据不同的记录调用getScore()
        AnalyzeDataObj currentObj = userAnswerService.getScore(currentRecord.getPaperId(), currentRecord.getDelFlag(),currentId);
        AnalyzeDataObj historyObj = userAnswerService.getScore(historyRecord.getPaperId(), historyRecord.getDelFlag(),historyId);
        Map<String, AnalyzeDataObj> map = new HashMap<>();
        map.put("current", currentObj);
        map.put("history", historyObj);
        return AjaxResult.success(map);
    }
}




